<?php

/**
 * This file is part of the Codizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Codizer Core Team <team@codizer.org>
 * @package     Codizer
 */

class f_core_Session
{
	private static $instance;
	
	/**
	 * @return f_core_Session
	 */
	private function __construct()
	{
        $manager = f_loader_Config::getInstance()->getParameter('default', 'sessionManager', 'file');

        if($manager == 'database')
        {
            f_session_Database::getInstance();
        }

		session_start();
		return $this;
	}
	
	/**
	 * Get singleton instance
	 *
	 * @return f_core_Session
	 */
	public static function getInstance()
	{
		if(self::$instance === null)
		{
			self::$instance = new self();
		}
		return self::$instance;
	}
	
	/**
	 * Retrieve the current session name
	 *
	 * @return string
	 */
	public function getSessionId()
	{
		return session_id();
	}
	
	/**
	 * Set a value in session
	 *
	 * @param string $name
	 * @param mixed $values
	 * @return f_core_Session
	 */
	public function setValue($name, $values)
	{
		if(!is_null($name) && !is_null($values))
		{
			$_SESSION[$name] = $values;	
		}
		return $this;
	}
	
	/**
	 * Get a value in session
	 *
	 * @param string $name
	 * @return mixed or null
	 */
	public function getValue($name, $defaultValue = null)
	{
		if(!is_null($name) && isset($_SESSION[$name]))
		{
			return $_SESSION[$name];
		}
		return $defaultValue;
	}
	
	/**
	 * Destroy a parameter in session
	 *
	 * @param string $name
	 */
	public function unsetValue($name)
	{
		unset($_SESSION[$name]);
	}
	
	/**
	 * Restart the session
	 */
	public function cleanSession()
	{
		session_unset();
	}

	/**
	 * Destroy the session
	 */
	public function destroySession()
	{
		session_destroy();
	}
	
	// Session Timer
	public function sessionTimeOut($time)
	{
		if($time > 0 && $time != null)
		{			
			$sessionLife = time() - $_SESSION['timeOut'];
			
			if($sessionLife > $time)
			{ 
				$this->cleanSession();
			}
			
			$_SESSION['timeOut'] = time();
		}
	}
}